<template>
  <div>
    <el-card class="box-card">
      <div slot="header">
        {{ $route.query.id ? '试题修改' : '试题录入' }}
      </div>
      <div class="text item">
        <el-form
          label-width="150px"
          :rules="reRules"
          :model="reForm"
          ref="form"
          required
        >
          <!-- 学科 -->
          <el-form-item label="学科:" prop="subjectID">
            <el-select
              class="el-select--medium"
              v-model="reForm.subjectID"
              @change="getlistId"
              @focus="handle"
            >
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="item in subjectList"
                :key="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item label="目录:" prop="catalogID">
            <el-select class="el-select--medium" v-model="reForm.catalogID">
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="item in directorysList"
                :key="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item label="企业:" prop="enterpriseID">
            <el-select class="el-select--medium" v-model="reForm.enterpriseID">
              <el-option
                :label="item.company"
                :value="item.id"
                v-for="item in enterpriseList"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 -->
          <el-form-item label="城市:" prop="province">
            <el-select
              class="el-select-w"
              v-model="reForm.province"
              @change="currentCity"
              @focus="handle1"
            >
              <el-option
                :label="item"
                :value="item"
                v-for="item in provinceList"
                :key="item"
              ></el-option>
            </el-select>
            <!-- 地区 -->
            <el-select class="el-select-lw" v-model="reForm.city">
              <el-option
                :label="item"
                :value="item"
                v-for="item in cityList"
                :key="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item label="方向:" prop="direction">
            <el-select class="el-select--medium" v-model="reForm.direction">
              <el-option
                :label="item"
                :value="item"
                v-for="item in directionList"
                :key="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item label="题型：" required>
            <el-radio-group v-model="reForm.questionType">
              <el-radio
                v-for="item in questionTypeList"
                :key="item.num"
                :label="item.num"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <!-- 难度单选框 -->
          <el-form-item label="难度：" required>
            <el-radio-group v-model="reForm.difficulty">
              <el-radio
                v-for="item in difficultyList"
                :key="item.num"
                :label="item.num"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item label="题干:" prop="question">
            <quill-editor
              :options="editorOption"
              v-model="reForm.question"
              @blur="checkQustion"
            />
          </el-form-item>
          <!-- 选项 -->
          <el-form-item
            label="选项："
            prop="options"
            v-if="reForm.questionType !== '3'"
          >
            <div
              class="option_item"
              v-for="item in reForm.options"
              :key="item.code"
            >
              <el-radio
                v-if="reForm.questionType === '1'"
                v-model="item.isRight"
                style="margin-right:0"
                :label="true"
                >{{ item.code }}：</el-radio
              >
              <el-checkbox
                v-if="reForm.questionType === '2'"
                v-model="item.isRight"
                style="margin-right:0"
                :label="true"
                >{{ item.code }}：</el-checkbox
              >
              <el-input v-model="item.title" style="width:240px"></el-input>
              <el-upload
                style="margin-left:4px"
                class="avatar-uploader"
                action="http://localhost:3001/upload"
                :show-file-list="false"
                :on-success="
                  (res, file) => {
                    uploadSuccess(item, res, file)
                  }
                "
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="item.img" :src="item.img" class="avatar" />
                <span v-else>上传图片</span>
                <i class="el-icon-circle-close"></i>
              </el-upload>
            </div>
            <!-- 添加按钮 -->
            <el-button
              type="danger"
              :disabled="flag || reForm.questionType !== '2'"
              @click="butClick"
              size="small"
              >+增加选项与答案</el-button
            >
          </el-form-item>

          <!-- 解析视频 -->
          <el-form-item label="解析视频">
            <el-input
              v-model="reForm.videoURL"
              class="el-select--medium"
            ></el-input>
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item label="答案解析:" prop="answer">
            <quill-editor
              :options="editorOption"
              v-model="reForm.answer"
              @blur="checkAnswer"
            />
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="题目备注:">
            <el-input
              type="textarea"
              :rows="4"
              id="text-textarea"
              v-model="reForm.remarks"
            >
            </el-input>
          </el-form-item>
          <!-- 试题标签 -->
          <el-form-item label="试题标签：">
            <el-select
              style="width:400px"
              v-model="reForm.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择试题标签"
            >
              <el-option
                v-for="item in labels"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-button v-if="!$route.query.id" @click="submit" type="primary"
              >确认提交</el-button
            >
            <el-button v-else @click="update" type="success"
              >确认修改</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { simple as directorysSimple } from '@/api/hmmm/directorys'
import { simple as subjectsSimple } from '@/api/hmmm/subjects'
import { list as companyList } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction } from '@/api/hmmm/constants'
import { add, detail as allDetail, update } from '@/api/hmmm/questions'
import { simple as getTags } from '@/api/hmmm/tags'
// import hljs from 'highlight.js'
import 'highlight.js/styles/dracula.css'

export default {
  name: 'questionsNew',
  data() {
    return {
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序列表，无序列表
            ['blockquote', 'code-block'], // 引用，代码块
            ['image', 'link'] // 图片 链接
          ]
        }
      },
      options: {
        optionA: '',
        optionB: '',
        optionC: '',
        optionD: ''
      },
      // 试题对象
      reForm: {
        // 学科id
        subjectID: null,
        // 目录id
        catalogID: null,
        // 企业列表
        enterpriseID: null,
        // 城市列表
        province: null,
        // 地区列表
        city: null,
        // 方向
        direction: null,
        // 题型
        questionType: '1',
        // 难度
        difficulty: '1',
        // 题干
        question: null,
        // 选项
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        // 解析视频
        videoURL: null,
        // 答案解析
        answer: null,
        // 题目备注
        remarks: null,
        // 试题标签
        tags: null
      },
      // 校验规则
      reRules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        city: [{ required: true, message: '请选择地区', trigger: 'change' }],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [
          {
            required: true,
            message: '请输入题干',
            trigger: 'change'
          }
        ]
      },
      // 学科列表
      subjectList: [],
      // 目录列表
      directorysList: [],
      // 企业列表
      enterpriseList: [],
      // 城市列表
      provinceList: [],
      // 地区列表
      cityList: [],
      // 方向列表
      directionList: [],
      // 题型
      questionTypeList: [
        {
          name: '单选',
          num: '1'
        },
        {
          name: '多选',
          num: '2'
        },
        {
          name: '简答',
          num: '3'
        }
      ],
      // 难度
      difficultyList: [
        {
          name: '简答',
          num: '1'
        },
        {
          name: '一般',
          num: '2'
        },
        {
          name: '困难',
          num: '3'
        }
      ],

      // 试题标签
      labels: [],
      // 控制button是否禁用
      flag: false
    }
  },
  components: {},
  created() {
    // 学科列表
    this.getList()
    // 企业列表
    this.getEnterpriseList()
    // 城市列表
    this.getCityData()
    this.getdirection()
    // 是否跳转
    if (this.$route.query.id) {
      this.subjectTotal(this.$route.query.id)
    }
  },
  methods: {
    // 列表
    async getList() {
      try {
        const { data } = await subjectsSimple()
        this.subjectList = data
      } catch (err) {
        console.log(err)
      }
    },

    // 根据列表id来显示该目录下的列表
    async getlistId() {
      const { data } = await directorysSimple({
        subjectID: this.reForm.subjectID
      })
      this.directorysList = data
      const res = await getTags({ subjectID: this.reForm.subjectID })
      this.labels = res.data
    },
    // 企业列表
    async getEnterpriseList() {
      try {
        const { data } = await companyList({
          pagesize: 10000
        })
        this.enterpriseList = data.items
      } catch (err) {
        console.log(err)
      }
    },
    // 获取省
    getCityData() {
      this.provinceList = provinces()
    },
    // 选省获取到市
    currentCity() {
      this.cityList = citys(this.reForm.province)
    },
    // 方向
    getdirection() {
      this.directionList = direction
    },
    // 提交
    submit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const data = { ...this.reForm }
          data.tags = data.tags.join(',')
          await add(data)
          this.$message.success('添加成功')
          this.$router.push('/questions/list')
        }
      })
    },
    // 校验题干
    checkQustion() {
      this.$refs.form.validateField('question')
    },
    // 效验答案解析
    checkAnswer() {
      this.$refs.form.validateField('answer')
    },
    butClick() {
      this.reForm.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.reForm.options.length),
        title: '',
        img: ''
      })
      if (this.reForm.options.length >= 8) {
        this.flag = !this.flag
        this.$message('最多添加8个')
      }
    },
    // 试题详情
    async subjectTotal(id) {
      const { data } = await allDetail({ id })
      this.reForm = data
      this.reForm.catalogID = this.reForm.directoryName
      this.reForm.options.forEach((item, index) => {
        if (item.isRight) {
          this.reForm.options[index].isRight = true
        }
      })
      this.reForm.tags = this.reForm.tags.split(',')
      const data1 = await directorysSimple({
        subjectID: this.reForm.subjectID
      })
      const arr = data1.data
      arr.forEach((item, index) => {
        if (item.label === this.reForm.catalogID) {
          this.reForm.catalogID = item.value
        }
      })
    },

    // 修改上传
    async update() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const data = { ...this.reForm }
          console.log(data, 11)
          data.tags = data.tags.join(',')
          await update(data)
          this.$message.success('修改成功')
          this.$router.push('/questions/list')
        }
      })
    },
    // 上传图片
    uploadSuccess(item, res, file) {
      // res 是相应对象
      // file 选择后的文件对象   file.raw 原始文件对象
      // URL.createObjectURL(file.raw)  本地预览地址
      // item 就是当前的选项对象
      item.img = URL.createObjectURL(file.raw)
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 清空目录
    async handle() {
      this.reForm.catalogID = ''
      const { data } = await directorysSimple({
        subjectID: this.reForm.subjectID
      })
      this.directorysList = data
    },
    // 清空城市
    handle1() {
      this.reForm.city = ''
      this.cityList = citys(this.reForm.province)
    }
  },
  watch: {
    reForm: {
      // 深度监听，可监听到对象、数组的变化
      handler(val, oldVal) {
        this.getlistId()
        this.currentCity()
      },
      deep: true // true 深度监听
    }
  }
}
</script>

<style scoped lang="less">
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.option_item {
  margin-bottom: 15px;
}
.demonstration {
  display: block;
  color: #8492a6;
  font-size: 14px;
  margin-bottom: 20px;
}
.el-select--medium {
  width: 400px !important;
}
.el-select-w {
  width: 198px !important;
}
.el-select-lw {
  width: 198px !important;
  margin-left: 4px;
}
/deep/.ql-editor {
  height: 200px !important;
}
/deep/#text-textarea {
  width: 400px;
}
.redio-input {
  width: 240px;
}
ins {
  text-decoration: none;
}
.avatar-uploader {
  position: relative;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: inline-block;
  width: 100px;
  margin-left: 5px;
  line-height: 60px;
  height: 60px;
  text-align: center;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.el-icon-circle-close {
  position: absolute;
  top: -8px;
  right: -6px;
  font-size: 18px;
  background: white;
}
.options-bottom {
  padding-bottom: 20px;
  height: 60px;
}
.el-radio {
  margin-right: 7px;
}
.color-button {
  background: #fab6b6;
  color: #fff;
  font-size: 12px;
}

.color-button:hover {
  background: #fab6b6;
  color: #fff;
}
.el-form-item__label {
  width: 155px;
}
.avatar {
  width: 100px;
  height: 60px;
}
</style>
